import io from 'socket.io-client';


class Socket {
  connection: any = null;
  ops: any = {};
  constructor(options: {} = {}) {
    this.ops = { ...options };
    this.openConnection();
    return this.connection;
  }

  openConnection() {
    try {
      const url = this.ops.url || 'http://127.0.0.1:3006';
      this.connection = io.connect(url, {
        transports: ['websocket', 'xhr-polling', 'jsonp-polling']
      });
      console.log('connection 3006');
    } catch (error) {
      console.log('open connection error');
    }

    this.connection.on('connect', this.onConnect);
    this.connection.on('error', this.onError);
    this.connection.onclose = this.handleClose;
    this.connection.on('disconnect', this.onDisconnect);
    this.connection.on('message', this.onMessage);
    this.connection.on('onuserconnect', this.onConnectMessage);
    this.connection.on('update', this.onUpdate);
  }

  onConnect = () => {
    console.log('in on connent');
    this.connection.emit('userconnect', 'success');
  };

  onDisconnect = () => {
    console.log('in disconnect');
    setTimeout(this.openConnection.bind(this), 500);
  };

  onMessage = (msg) => {
    this.ops.onMessage && this.ops.onMessage(msg);
  };

  onConnectMessage = (msg) => {
    this.ops.onConnectMessage && this.ops.onConnectMessage(msg);
  };

  onUpdate = (msg) => {
    this.ops.onUpdate && this.ops.onUpdate(msg);
  };

  onError = (event) => {
    console.log(`Websocket connection error: ${JSON.stringify(event)}`);
  };

  handleClose = (e) => {
    console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
    console.log(e);
  };

  close = () => {
    if (
      this.connection &&
      this.connection.readyState !== 'CLOSING' &&
      this.connection.readyState !== 'CLOSED'
    ) {
      this.connection.onclose = () => {};
      this.connection.onerror = () => {};
      this.connection.close();
    }
  };
}

export default Socket;
